<?php

namespace App\Console\Commands;

use App\Models\Area;
use Illuminate\Console\Command;
use App\Common\Common;
use Exception;
use App\Jobs\SyncSendSms;

class ExportArea extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'export:area';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $data = $this->buildLevel('CN');
        file_put_contents(public_path().'/area.json',json_encode($data,JSON_UNESCAPED_UNICODE));
    }

    private function buildLevel($root,$level=3){
        if($level<=0) return null;
        $data = [];
        Area::where('pcode',$root)->get()->each(function ($area)use(&$data,$level){
            $data[] = [
                'value' => $area->code,
                'text' => $area->name,
                'children' => $this->buildLevel($area->code,--$level),
            ];
        });
        return $data;
    }

}
